﻿using DBManager.Helper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;

namespace DBManager.UserCode
{
    public class XmlCommon
    {
        public static void CreateXmlTree(string xmlFilePath, string xmlStr)
        {
            FileHelper.DeleteFile(xmlFilePath);
            XElement xElement = XElement.Parse(xmlStr);
            //需要指定编码格式，否则在读取时会抛：根级别上的数据无效。 第 1 行 位置 1异常
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Encoding = new UTF8Encoding(false);
            settings.Indent = true;
            XmlWriter xw = XmlWriter.Create(xmlFilePath, settings);
            xElement.Save(xw);
            //写入文件
            xw.Flush();
            xw.Close();
        }

        /// <summary>
        /// 获取指定数据库下所有表
        /// </summary>
        /// <param name="dbName"></param>
        /// <returns></returns>
        public static List<string> SelectDtList(string xmlFilePath, string dbName)
        {
            List<string> list = new List<string>();
            if (FileHelper.IsExistFile(xmlFilePath))
            {
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(xmlFilePath);
                //取指定的结点的集合
                XmlNodeList nodes = xmlDoc.SelectNodes("dblist/db[@dbname='" + dbName + "']/dt");
                if (nodes.Count > 0)
                {
                    foreach (XmlNode node in nodes)
                    {
                        list.Add(node.InnerText);
                    }
                }
            }
            return list;
        }
    }
}
